<!-- 撤销电子证书 -->
<template>
  <el-dialog
    :title="dialogTitle"
    :visible="visible"
    width="1500px"
    @close="handleClose"
    append-to-body
  >
    <el-form ref="form" :model="form" label-width="120px">
      <!-- 证书列表 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-table
            :data="certificateList"
            border
            style="width: 100%"
            :header-cell-style="{ background: '#f5f7fa' }"
          >
            <el-table-column
              prop="certificateNo"
              label="证书编号"
              width="180"
            />
            <el-table-column prop="studentName" label="姓名" width="120" />
            <el-table-column prop="documentNo" label="证件编号" width="180" />
            <el-table-column prop="templateName" label="证书模板">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.certificateTemplateId"
                  placeholder="请选择模板"
                  @change="handleTemplateChange(scope.row, $event)"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="template in templateList"
                    :key="template.certificateTemplateId"
                    :label="template.certificateTemplateName"
                    :value="template.certificateTemplateId"
                  >
                    {{ template.certificateTemplateName }}
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </el-col>

        <!-- 预览区域 -->
        <el-col :span="12">
          <div class="preview-container">
            <div class="preview-header">
              <span>预览</span>
            </div>
            <div class="preview-content">
              <div class="embedded-preview">
                <CertificateTemplatePreview
                  v-if="previewData"
                  :template-data="previewData"
                />
                <div v-else class="no-preview">请选择模板以预览</div>
              </div>
            </div>

            <!-- 分页控件 -->
            <div class="certificate-switch" v-if="certificateList.length > 1">
              <div class="pagination-wrapper">
                <el-pagination
                  small
                  layout="prev, pager, next"
                  :total="certificateList.length"
                  :current-page="currentPage"
                  :page-size="1"
                  @current-change="handlePageChange"
                />
              </div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 撤销原因 -->
      <el-form-item label="撤销原因" prop="revokeReason">
        <el-input
          v-model="form.revokeReason"
          type="textarea"
          :rows="4"
          placeholder="请输入撤销原因"
          style="width: 500px"
        />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="submit">撤销</el-button>
    </div>
  </el-dialog>
</template>

<script>
import CertificateTemplatePreview from "@/components/Certificate/issue/CertificateTemplatePreview.vue";
import { getCertificateTemplateInfo } from "@/api/certificate/certificateTemplate";

export default {
  name: "RevokeElectronicCertificateDialog",
  components: {
    CertificateTemplatePreview,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    certificateData: {
      type: Array,
      default: () => [],
    },
    templateList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      dialogTitle: "撤销电子证书",
      form: {
        revokeReason: "",
      },
      certificateList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      currentPreviewItem: {}, // 当前预览项
      previewData: null, // 预览数据
    };
  },
  computed: {
    // 获取当前选中的证书
    currentCertificate() {
      return this.certificateList[this.currentPage - 1] || {};
    },
    previewWithCertificateData() {
      if (!this.previewData || !this.currentCertificate) {
        return null;
      }

      return {
        ...this.previewData,
        certificateData: this.currentCertificate,
      };
    },
  },
  watch: {
    visible(val) {
      if (val) {
        this.initData();
        // 页面打开时，如果证书列表有数据，自动加载第一个证书的模板预览
        if (
          this.certificateList.length > 0 &&
          this.certificateList[0].certificateTemplateId
        ) {
          this.loadTemplatePreview(
            this.certificateList[0].certificateTemplateId
          );
        }
      }
    },
    certificateData: {
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.certificateList = newVal.map((item) => {
            const mappedItem = {
              ...item,
              certificateTemplateId: item.templateId || null, // 注意这里字段名映射
            };

            // 如果存在templateId，则从templateList中查找对应的模板名称进行回显
            if (
              mappedItem.certificateTemplateId &&
              this.templateList.length > 0
            ) {
              const matchedTemplate = this.templateList.find(
                (template) =>
                  template.certificateTemplateId ===
                  mappedItem.certificateTemplateId
              );
              if (matchedTemplate) {
                mappedItem.templateName =
                  matchedTemplate.certificateTemplateName;
              }
            }

            return mappedItem;
          });
        }
      },
      deep: true,
      immediate: true,
    },
    templateList: {
      handler(newVal) {
        // 当模板列表更新时，重新处理已选证书的模板名称回显
        if (newVal && newVal.length > 0 && this.certificateList.length > 0) {
          this.certificateList = this.certificateList.map((item) => {
            if (item.certificateTemplateId) {
              const matchedTemplate = newVal.find(
                (template) =>
                  template.certificateTemplateId === item.certificateTemplateId
              );
              if (matchedTemplate) {
                return {
                  ...item,
                  templateName: matchedTemplate.certificateTemplateName,
                };
              }
            }
            return item;
          });
        }
      },
      immediate: true,
    },
  },
  methods: {
    // 处理模板选择变化
    handleTemplateChange(row, templateId) {
      if (templateId) {
        const selectedTemplate = this.templateList.find(
          (template) => template.certificateTemplateId === templateId
        );
        if (selectedTemplate) {
          // 直接修改行数据，确保响应式更新
          row.certificateTemplateId = templateId;
          row.templateName = selectedTemplate.certificateTemplateName;

          // 如果当前显示的是这个证书，则更新预览
          if (row === this.currentCertificate) {
            this.loadTemplatePreview(templateId);
          }
        }
      } else {
        // 清空选择时重置数据
        row.certificateTemplateId = null;
        row.templateName = "";

        // 如果当前显示的是这个证书，则清空预览
        if (row === this.currentCertificate) {
          this.previewData = null;
        }
      }
    },

    // 分页切换处理
    handlePageChange(page) {
      this.currentPage = page;
      const certificate = this.certificateList[page - 1];
      if (certificate && certificate.certificateTemplateId) {
        this.loadTemplatePreview(certificate.certificateTemplateId);
      } else {
        this.previewData = null;
      }
    },

    // 根据模板ID加载模板配置并更新预览
    async loadTemplatePreview(templateId) {
      try {
        const res = await getCertificateTemplateInfo(templateId);
        let templateData = null;
        if (res.data.rows) {
          templateData = res.data.rows.find(
            (item) => item.certificateTemplateId === templateId
          );
        } else {
          templateData = res.data;
        }

        if (!templateData) {
          throw new Error(`未找到模板ID为 ${templateId} 的模板`);
        }

        // 设置预览数据
        this.previewData = {
          ...templateData,
          backgroundUrl: templateData.backgroundUrl || "",
          certificateFieldList: templateData.certificateFieldList || [],
        };

        // 更新当前证书的模板信息
        if (
          this.currentCertificate &&
          this.currentCertificate.certificateTemplateId === templateId
        ) {
          this.currentCertificate.templateName =
            templateData.certificateTemplateName;
        }
      } catch (error) {
        console.error("加载模板失败:", error);
        this.previewData = null;
        this.$message.error("模板加载失败，请检查网络连接或联系管理员");
      }
    },

    initData() {
      this.form = {
        revokeReason: "",
      };
      this.currentPage = 1;
      this.previewData = null;
    },

    handleClose() {
      this.$emit("update:visible", false);
    },

    cancel() {
      this.handleClose();
    },

    submit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.$emit("submit", {
            revokeReason: this.form.revokeReason,
            certificateIssueList: this.certificateList.map((item) => ({
              certificateIssueId: item.certificateIssueId,
              templateId: item.certificateTemplateId,
            })),
          });
          this.handleClose();
        }
      });
    },
  },
};
</script>

<style scoped>
.preview-container {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  height: 500px;
}

.preview-header {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.preview-content {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.embedded-preview {
  width: 100%;
  height: 100%;
  position: relative;
}

.no-preview {
  display: flex;
  justify-content: center;
  align-items: center;
  color: #999;
  font-size: 14px;
}

/* 分页控件样式 */
.certificate-switch {
  margin-top: 10px;
}

.pagination-wrapper {
  text-align: center;
}

:deep(.view-certificate-dialog) {
  box-shadow: none;
  border: none;
  width: 100% !important;
  height: 100% !important;
}

:deep(.action-buttons) {
  display: none;
}

:deep(.certificate-container) {
  width: 100% !important;
  height: 100% !important;
}

:deep(.certificate-bg) {
  width: 100% !important;
  height: 100% !important;
}

:deep(.bg-image) {
  width: 100% !important;
  height: 100% !important;
}
</style>
